package com.example.xksys.utils.graph;


import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

public class CheckCode {
protected String color;
protected int width,height;
protected int splitWidth;
protected int nDots;
protected String code;
protected BufferedImage bimg;
protected Graphics g;
public static char codeSet[]=new char[] {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','1','2','3','4','5','6','7'
		,'8','9','0'};

public CheckCode(int w,int h,int splitWidth,int nDots)
{
	this.code="";
	this.width=w;
	this.height=h;
	this.splitWidth=splitWidth;
	this.nDots=nDots;
	bimg=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
	g=bimg.getGraphics();
}
public String formImage()
{
	g.setColor(Color.orange);
	g.fillRect(0, 0, this.width, this.height);
	g.setColor(Color.blue);
	Gpos gp=new Gpos(this.width,this.height);
	for(int i=0;i<nDots;i++) {
		gp.newGpos();
		g.setColor(gp.getC());
		g.fillOval(gp.getX(), gp.getY(), 2, 2);
	}

	g.setColor(Color.blue);
	g.setFont(new Font(null,Font.ITALIC,18));
	gp=new Gpos(codeSet.length-1,this.height-18);
	for(int i=0;i<this.width;i+=this.splitWidth)
	{		
		gp.newGpos();
		String codes=""+codeSet[gp.getX()];
		this.code+=codes;
		g.drawString(codes, i, this.height-gp.getY()-3);
	}
	return this.code;
	
	
}
public void setServlertResponse(HttpServletRequest request,HttpServletResponse response) throws IOException
{
	response.setContentType("image/jpeg");
	response.setHeader("Pragma", "No-cache");
	response.setHeader("Cache-Control", "no-cache");
	response.setDateHeader("Expires", 0);
	HttpSession session=request.getSession();
	session.setAttribute("codeStr", this.code);
	ServletOutputStream sos=response.getOutputStream();
	ByteArrayOutputStream baos=new ByteArrayOutputStream();
	ImageIO.write(this.bimg,"JPEG",baos);
	byte[] bytes=baos.toByteArray();
	response.setContentLength(bytes.length);
	sos.write(bytes);
	sos.close();
	baos.close();
}
public void WriterFile(String path) throws  IOException
{
	File f=new File(path);
	if(!f.exists())f.createNewFile();
	ImageIO.write(this.bimg, "JPEG",f);
}
}
